goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.dom.classes');
goog.require('goog.events');

goog.provide('ObjectList');

/**
 * @constructor
 */
ObjectList = function(baseName, element) {
    this.baseName = baseName;
    this.element = element;
    this.textPieces = Array();
    goog.dom.classes.add(this.element, 'objlist-container');
    goog.dom.setTextContent(this.element, '[None]');
};

ObjectList.prototype.addElement = function(text) {
    // Clear it of any "None"-style text.
    if (this.textPieces.length == 0) {
	goog.dom.setTextContent(this.element, "");
    }
    var objectElement = goog.dom.createElement('span');
    var inputElem = goog.dom.createElement('input');
    inputElem.name = this.baseName;
    inputElem.value = text;
    goog.style.showElement(inputElem, false);
    
    goog.dom.classes.add(objectElement, 'objlist-element');
    var closeButton = goog.dom.createElement('span');
    goog.dom.setTextContent(closeButton, '✘');
    goog.dom.classes.add(closeButton, 'objlist-close-button');
    goog.style.showElement(closeButton, true);
    goog.events.listen(closeButton, goog.events.EventType.CLICK,
		       goog.bind(this.removeElement, this, objectElement),
		       false);
    var textElement = goog.dom.createDom('span', 'objlist-textelement');
    goog.dom.setTextContent(textElement, text);
    goog.dom.appendChild(objectElement, textElement);
    goog.dom.appendChild(objectElement, closeButton);
    goog.dom.appendChild(objectElement, inputElem);
    goog.dom.appendChild(this.element, objectElement);
    this.textPieces.push(text);
};

ObjectList.prototype.removeElement = function(element) {
    var textElement = goog.dom.getElementsByTagNameAndClass(
	'span', 'objlist-textelement', element)[0];
    goog.dom.removeNode(element);
    var currText = goog.dom.getTextContent(textElement);
    for (var i in this.textPieces) {
	if (this.textPieces[i] == currText) {
	    this.textPieces.splice(i, 1);
	    window.console.log('Removin ya.');
	    break;
	}
    }
    if (this.textPieces.length == 0) {
	goog.dom.setTextContent(this.element, "[None]");
    }
};

